import React from 'react';
import axios from 'axios'
import './Duanzi.css'
import { useState } from 'react';
import { useEffect } from 'react';

function Duanzi(props) {
    let [data, setData] = useState([]);
    let [mask, setMask] = useState(false);
    let [modeldata, setModeldata] = useState();

    let view = (item) => {
        return () => {
            setMask(true);
            // 传数据
            setModeldata(item);
        }
    }

    let back = () => {
        setMask(false);
    }

    // 模拟挂载componentDidMount()
    useEffect(() => {
        // 请求数据
        async function main() {
            let result = await axios.get('http://api.xiaohigh.com/duanzi');
            setData(result.data.slice(0, 20));
        };
        main();
    }, [])

    return (
        <div className='duanzi'>
            <ul>
                {
                    data.map((item) => {
                        return (
                            <li key={item.id} onClick={view(item)}>
                                <h2>{item.name}</h2><hr />
                                <p>{item.text.length >= 80 ? `${item.text.slice(0, 80)} + '...` : item.text}</p>
                            </li>
                        )
                    })
                }
            </ul>
            {/* 遮罩和弹窗 */}
            {
                mask ? (
                    <div>
                        <div className='mask'></div>
                        <div className='model'>
                            <span className='back' onClick={back}>X</span>
                            <h2>{modeldata.name}</h2>
                            <hr />
                            <p>{modeldata.text}</p>
                        </div>
                    </div>
                ) : null
            }
        </div>
    );
}

export default Duanzi;